/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
*/

#include "Xern/FileSystem.hpp"
#include "Xern/FilterStream.hpp"
#include "GeometryInstance.hpp"
#include "Light.hpp"
#include "OgreRenderer.hpp"
#include "OgreLoader.hpp"

namespace XernOgre
{
	OgreLoader::OgreLoader(boost::shared_ptr<OgreRenderer> renderer)
		: renderer(renderer)
	{
	}

	OgreLoader::~OgreLoader()
	{
	}

	bool OgreLoader::CanLoadResource(const std::string &mime) const
	{
		if(mime == "application/vnd.xern.geom.instance")
			return true;
		else if(mime == "application/vnd.xern.light")
			return true;

		//if(mime == "application/x-ogre-mesh")
		//	return true;
		return false;
	}

	bool OgreLoader::CanLoadResource(const std::string &filename, const std::string &group) const
	{
		// Check for special groups.
		if(group == "Particles")
			return true;

		std::string extension = FileExtension(filename);
		return extension == ".mesh";
	}

	boost::shared_ptr<IResource>
	OgreLoader::LoadResource(const std::string &filename, const std::string &group, const std::string &path) const
	{
		assert(CanLoadResource(filename, group));

		// Check for special groups.
		if(group == "Particles")
		{
			return renderer->CreateParticleSystem(filename);
		}

		// Check for extensions.
		std::string extension = FileExtension(filename);
		if(extension == ".mesh")
		{
			return renderer->CreateGeometry(filename, group);
		}

		return boost::shared_ptr<IResource> ();
	}

	boost::shared_ptr<IResource>
	OgreLoader::LoadResource(const std::string &mime, boost::shared_ptr<IDataFilter> data) const
	{
		assert(CanLoadResource(mime));

		if(mime == "application/vnd.xern.geom.instance")
		{
			// Create the filter stream
			FilterStream in(data);

			// Read the json object.
			JsonObject object;
			in >> object;

			// Load the resource.
			return GeometryInstance::LoadInstance(renderer, object);
		}
		else if(mime == "application/vnd.xern.light")
		{
			// Create the filter stream
			FilterStream in(data);

			// Read the json object.
			JsonObject object;
			in >> object;

			// Load the resource.
			return Light::LoadLight(renderer, object);
		}

		return boost::shared_ptr<IResource> ();
	}

}
